package org.example.service.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.example.mapper.TopicAboutCompanyMapper;
import org.example.pojo.entity.TopicAboutCompany;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.io.BufferedReader;
import java.io.FileReader;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.List;
import java.util.Random;
import java.time.temporal.ChronoUnit;

@Service
public class TopicAboutCompanyServiceImpl extends ServiceImpl<TopicAboutCompanyMapper, TopicAboutCompany> {

    @Transactional(rollbackFor = Exception.class)
    public void importTopicsFromFile() {
        try (BufferedReader reader = new BufferedReader(new FileReader("src/新建 文本文档.txt"))) {
            List<TopicAboutCompany> topics = new ArrayList<>();
            String line;
            int lineNumber = 0;
            Random random = new Random();
            
            // 获取当前时间
            LocalDateTime now = LocalDateTime.now();
            // 获取30天前的时间
            LocalDateTime thirtyDaysAgo = now.minus(30, ChronoUnit.DAYS);
            
            while ((line = reader.readLine()) != null) {
                if (line.trim().isEmpty()) continue;
                
                lineNumber++;
                String companyName = determineCompanyName(lineNumber);
                
                // 生成随机时间（在过去30天内）
                long randomSeconds = random.nextLong(ChronoUnit.SECONDS.between(thirtyDaysAgo, now));
                LocalDateTime randomTime = thirtyDaysAgo.plus(randomSeconds, ChronoUnit.SECONDS);
                String formattedTime = randomTime.format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"));
                
                TopicAboutCompany topic = new TopicAboutCompany();
                topic.setCompanyName(companyName);
                topic.setTopicContent(line.trim());
                topic.setTime(formattedTime);
                
                topics.add(topic);
                
                // 每20条数据批量插入一次
                if (topics.size() >= 20) {
                    saveBatch(topics);
                    topics.clear();
                }
            }
            
            // 保存剩余的数据
            if (!topics.isEmpty()) {
                saveBatch(topics);
            }
        } catch (Exception e) {
            throw new RuntimeException("导入面试题失败: " + e.getMessage(), e);
        }
    }
    
    private String determineCompanyName(int lineNumber) {
        if (lineNumber <= 20) {
            return "阿里巴巴";
        } else if (lineNumber <= 40) {
            return "腾讯";
        } else if (lineNumber <= 60) {
            return "美团";
        } else if (lineNumber <= 80) {
            return "百度";
        } else {
            return "网易";
        }
    }
} 